<template>
  <div>
    <r-search :searchHandle="searchHandleAdd" />
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <r-table
      :isSelection="false"
      :isIndex="true"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      @refresh="init()"
    ></r-table>

    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules"
      :formCols="formCols"
      :formHandle="formHandle"
      :formData="formData"
      ref="elForm"
      :inline="false"
      dialogWidth="850px"
    >
      <!--            <div :slot="'door'+(index+1)" v-for="(item,index) in callLists" :key="index">-->
      <!--                <span v-for="(item2,index2) in item" :key="index2" style="margin-right:10px;margin-bottom:10px;float:left;cursor: pointer;">-->
      <!--                    <el-tag @click="callClick(item2,index)" :type="item2.type">{{index2+1}}号称</el-tag>-->
      <!--                </span>-->
      <!--            </div>-->

      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"
        ></div>
        <p>
          点击地图拾取坐标 经度：{{ formData.longitude }} 纬度：{{
            formData.latitude
          }}
        </p>
        <div id="l-map"></div>
      </div>
    </r-form>
    <r-form
      :formRules="formRulesEditPsw"
      :formHandle="formHandleEditPsw"
      :formData="formDataEditPsw"
      :formCols="formColsEditPsw"
      ref="elFormEditPsw"
      labelWidth="200px"
      dialogWidth="1000px"
      :isHandle="true"
    />
    <r-form
      :formRules="formRulesActive"
      :formHandle="formHandleActive"
      :formData="formDataActive"
      :formCols="formColsActive"
      ref="elFormActive"
      labelWidth="200px"
      dialogWidth="1000px"
      :isHandle="true"
    />
  </div>
</template>

<script>
import baidumap from "../js/baidumap";
export default {
  data() {
    var checkpass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Enter Again PassWord"));
      } else if (value !== this.formData.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    var checkpass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Enter Again PassWord"));
      } else if (value !== this.formDataEditPsw.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    return {
      baiduMap: null,
      //
      searchData: {},
      searchForm: [
        {
          type: "input",
          prop: "name",
          placeholder: "商家Name",
          width: 150
        },
        {
          type: "input",
          prop: "phone",
          placeholder: "联系方式",
          width: 150
        },
        {
          type: "input",
          prop: "agentName",
          placeholder: "Agent Name",
          width: 170,
          isShow: e => (sessionStorage.getItem("role") == 3 ? false : true)
        },
        {
          type: "select",
          prop: "state",
          placeholder: "Status",
          width: 150,
          options: [
            {
              label: "Enable",
              value: "1"
            },
            {
              label: "Forbidden",
              value: "2"
            }
          ]
        }
      ],
      searchHandleAdd: [
        {
          label: "Add商家",
          type: "success",
          icon: "el-icon-circle-plus-outline",
          handle: e => this.createdAcc(),
          isShow: () => this.apis.showBtn(45, this)
        }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          icon: "el-icon-search",
          handle: e => this.init()
        },
        {
          label: "Reset",
          icon: "el-icon-refresh-right",
          handle: e => this.searchFromReset()
        }
      ],
      tableData: [],
      tableCols: [
        {
          label: "商家Name",
          prop: "name"
          // theme: e => e.status ? 'primary' : 'danger', type: "tag",
        },
        {
          label: "联系方式",
          prop: "phone"
        },
        {
          label: "登录账号",
          prop: "account"
        },
        {
          label: "所属上级",
          prop: "regionName"
        },
        {
          label: "总收益",
          prop: "totalRevenue"
        },
        {
          label: "可提Balance",
          prop: "withdrawMoney"
        },
        {
          label: "账号Status",
          prop: "state",
          formatter: e => (e.state == 1 ? "Enable" : "Forbidden"),
          theme: e => (e.state == 1 ? "primary" : "danger"),
          type: "tag"
        },
        {
          label: "Operations",
          type: "button",
          width: 400,
          dropList: [
            {
              label: "Forbidden账号",
              isShow: e =>
                e.state == 1 && this.apis.showBtn(48, this) ? true : false
            },
            {
              label: "恢复账号",
              isShow: e =>
                e.state == 2 && this.apis.showBtn(48, this) ? true : false
            },
            {
              label: "Change Password",
              isShow: () => this.apis.showBtn(49, this)
            },
            { label: "Delete", isShow: () => this.apis.showBtn(50, this) }
          ],
          dropSize: "mini",
          handleCommand: e => {
            if (e.btn == "Forbidden账号" || e.btn == "恢复账号") {
              this.elFormDetailActive(e.row);
            } else if (e.btn == "Change Password") {
              this.elFormDetailEditPsw(e.row);
            } else if (e.btn == "Delete") {
              this.TableDel("/merchant", { id: e.row.id }, "del");
            }
          },
          btnList: [
            {
              label: "Edit",
              type: "primary",
              // isShow: e => e.orderId == '123' ? true : false,
              handle: row => this.createdAcc(row),
              isShow: () => this.apis.showBtn(46, this)
            },
            {
              label: "账号Details",
              type: "primary",
              handle: row => {
                this.$router.push({
                  path: "/shop-sallerDetail",
                  query: { id: row.id }
                });
              },
              isShow: () => this.apis.showBtn(47, this)
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        name: "",
        phone: "",
        regionalId: "",
        account: "",
        password: "",
        enterPassword: "",
        proportion: "",
        proportion2: "",
        proportion3: "",
        proportion4: "",
        address: "",
        roleName: "",
        longitude: "",
        latitude: "",
        city: ""
      },
      formCols: [
        {
          type: "input",
          label: "商家Name",
          placeholder: "Please Input商家Name",
          width: 350,
          prop: "name"
        },
        {
          type: "input",
          label: "联系方式",
          placeholder: "Please Input联系方式",
          width: 200,
          prop: "phone"
        },
        {
          type: "select",
          label: "Belonging Agent商",
          placeholder: "Please SelectAgent",
          width: 350,
          prop: "regionalId",
          options: []
        },
        {
          type: "input",
          label: " 登录账号",
          placeholder: "Please Input登录账号",
          width: 350,
          prop: "account"
        },
        {
          type: "input",
          isShow: () => {
            return this.formData.id ? false : true;
          },
          label: " 密码",
          placeholder: "Please Input密码",
          width: 350,
          prop: "password"
        },
        {
          type: "input",
          isShow: () => {
            return this.formData.id ? false : true;
          },
          label: "确认密码",
          placeholder: "Please Input确认密码",
          width: 350,
          prop: "enterPassword"
        },
        {
          type: "input",
          label: "生鲜柜分成比例",
          placeholder: "Please Input生鲜柜分成比例",
          width: 350,
          prop: "proportion",
          remark: "%"
        },
        {
          type: "input",
          label: "自提商城分成比例",
          placeholder: "Please Enter",
          width: 350,
          prop: "proportion2",
          remark: "%"
        },
        {
          type: "input",
          label: "售袋分成比例",
          placeholder: "Please Input售袋分成比例",
          width: 350,
          prop: "proportion3",
          remark: "%"
        },
        {
          type: "input",
          label: "售卡分成比例",
          placeholder: "Please Input售卡分成比例",
          width: 350,
          prop: "proportion4",
          remark: "%"
        },
        {
          type: "input",
          id: "suggestId",
          label: "详细地址",
          width: 350,
          prop: "address"
        },
        { type: "slot", name: "slot3", label: "", prop: "longitude" }
      ],
      formRules: {
        name: [
          {
            required: true,
            message: "Please Input商家人员Name",
            trigger: "blur"
          }
        ],
        phone: [
          { required: true, message: "Please Input联系方式", trigger: "blur" }
        ],
        regionalId: [
          {
            required: true,
            message: "Please SelectBelonging Agent商",
            trigger: "blur"
          }
        ],
        account: [
          { required: true, message: "Please Input登录账号", trigger: "blur" }
        ],
        password: [
          {
            required: true,
            message: "Please Input密码",
            trigger: "blur",
            isShow: () => {
              return this.formData.id ? false : true;
            }
          }
        ],
        enterPassword: [
          {
            required: true,
            validator: checkpass,
            message: "请确认两次密码是否一致",
            trigger: "blur",
            isShow: () => {
              return this.formData.id ? false : true;
            }
          }
        ],

        proportion: [
          { required: true, message: "Please Input生鲜柜分成", trigger: "blur" }
        ],
        proportion2: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        proportion3: [
          { required: true, message: "Please Input售袋分成", trigger: "blur" }
        ],
        proportion4: [
          { required: true, message: "Please Input售卡分成", trigger: "blur" }
        ],
        address: [
          { required: true, message: "Please Input详细地址", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "请点击地图选择经纬度", trigger: "blur" }
        ]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      //密码
      formDataEditPsw: {
        password: "",
        enterPassword: ""
      },
      formColsEditPsw: [
        {
          type: "input",
          label: " 密码",
          placeholder: "Please Input密码",
          width: 350,
          prop: "password"
        },
        {
          type: "input",
          label: "确认密码",
          placeholder: "Please Input确认密码",
          width: 350,
          prop: "enterPassword"
        }
      ],
      formRulesEditPsw: {
        password: [{ required: true, message: "密码", trigger: "blur" }],
        enterPassword: [
          {
            required: true,
            validator: checkpass2,
            message: "请确认两次密码是否一致",
            trigger: "blur"
          }
        ]
      },
      formHandleEditPsw: [
        {
          label: "Cancel",
          handle: e => this.elFormVisibleEditPsw()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmitEditPsw()
        }
      ],
      //Forbidden恢复
      formDataActive: {
        isActive: ""
      },
      formRulesActive: {},
      formColsActive: [
        { label: "是否恢复/Forbidden选定账号", width: 350, prop: "isActive" }
        // { type: "input", label: "确认密码", placeholder: 'Please Input确认密码', width: 350, prop: "enterPassword" },
      ],
      formHandleActive: [
        {
          label: "Cancel",
          handle: e => this.elFormVisibleActive()
        },
        {
          label: "Confirm",
          type: "primary",
          handle: e => this.elFormSubmitActive()
        }
      ],
      checkBox: [],

      callLists: [[], []]
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      this.tablePage.offset = this.tablePage.page;
      let param = { ...this.tablePage, ...this.searchData };
      let res = await this.api.merchant(param);
      if (res) {
        this.tableData = res.data.list;
        this.tablePage.total = res.data.total;
      }
      let resOpt = await this.api.getOperatorList({});
      if (resOpt) {
        this.operatorId = resOpt.data.operatorId;
      }
      let resAgent = await this.api.agentlist({});
      if (resAgent) {
        this.formCols[2].options = [];
        for (let i = 0; i < resAgent.data.length; i++) {
          this.formCols[2].options.push({
            name: resAgent.data[i].name,
            value: resAgent.data[i].id
          });
        }
      }
    },
    callClick(item, index) {
      console.log(item);
      console.log(index);
      for (var i = 0; i < this.callLists.length; i++) {}
      item.type = "success";
    },
    map() {
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder();
      map.addEventListener("click", function(e) {
        that.formData.longitude = e.point.lng;
        that.formData.latitude = e.point.lat;

        var pt = e.point;
        geoc.getLocation(pt, function(rs) {
          var addComp = rs.addressComponents;
          that.formData.city = addComp.city;
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
      });
      map.enableScrollWheelZoom(); //Enable滚轮放大缩小，默认Forbidden
      map.enableContinuousZoom(); //Enable地图惯性拖拽，默认Forbidden
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 10);
      });
    },
    createdAcc(row) {
      this.elFormVisible().then(res => {
        this.map().then(res => {
          if (row) {
            Object.keys(this.formData).forEach(key => {
              this.formData[key] = row[key];
            });
            this.formData.id = row.id;
            this.formData.password = "";
          }
        });
      });
    },
    elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            let res = await this.api.merchantedit(this.formData);
            if (res) {
              this.init();
              this.elFormVisible();
            }
          } else {
            let res = await this.api.merchantadd(this.formData);
            if (res) {
              this.init();
              this.elFormVisible();
            }
          }
        }
      });
    },
    elFormDetail(row) {
      // this.elFormVisible()
    },
    elFormDetailEditPsw(row) {
      Object.keys(this.formDataEditPsw).forEach(key => {
        this.formDataEditPsw[key] = row[key];
      });
      this.formDataEditPsw.id = row.id;
      this.formDataEditPsw.regionalId = row.regionalId;
      this.formDataEditPsw.name = row.name;
      this.formDataEditPsw.phone = row.phone;
      this.formDataEditPsw.address = row.address;
      this.formDataEditPsw.longitude = row.longitude;
      this.formDataEditPsw.latitude = row.latitude;
      this.elFormVisibleEditPsw();
    },
    async elFormSubmitEditPsw() {
      let res = await this.api.merchantedit(this.formDataEditPsw);
      if (res) {
        this.init();
        this.elFormVisibleEditPsw();
      }
    },
    elFormVisibleEditPsw(tit) {
      if (this.$refs.elFormEditPsw.$refs.ruleFormEditPsw) {
        this.$refs.elFormEditPsw.$refs.ruleFormEditPsw.resetFields();
        this.$data.formDataEditPsw = this.$options.data.call(
          this
        ).formDataEditPsw;
      }
      this.$refs.elFormEditPsw.dialogFormVisible = !this.$refs.elFormEditPsw
        .dialogFormVisible;
      this.$refs.elFormEditPsw.dialogFormTitle = tit
        ? tit
        : this.formDataEditPsw.id
        ? "Edit"
        : "Add";

      if (this.$refs.elFormEditPsw.dialogFormVisible) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        });
      }
    },
    elFormDetailActive(row) {
      Object.keys(this.formDataActive).forEach(key => {
        this.formDataActive[key] = row[key];
      });
      this.formDataActive.id = row.id;
      this.elFormVisibleActive();
    },
    elFormVisibleActive(tit) {
      if (this.$refs.elFormActive.$refs.ruleFormActive) {
        this.$refs.elFormActive.$refs.ruleFormActive.resetFields();
        this.$data.formDataActive = this.$options.data.call(
          this
        ).formDataActive;
      }
      this.$refs.elFormActive.dialogFormVisible = !this.$refs.elFormActive
        .dialogFormVisible;
      this.$refs.elFormActive.dialogFormTitle = tit
        ? tit
        : this.formDataActive.id
        ? "Edit"
        : "Add";

      if (this.$refs.elFormActive.dialogFormVisible) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        });
      }
    },
    async elFormSubmitActive() {
      // console.log(this.formDataActive.id);
      let res = await this.api.merchantchange(this.formDataActive);
      if (res) {
        this.init();
        this.elFormVisibleActive();
      }
    }
  }
};
</script>

<style scoped lang="scss">
#l-map {
  height: 250px;
  width: 100%;
}
#r-result {
  width: 100%;
}
</style>
